var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');

Page({
  data: {
    orderId: 0,
    orderInfo: {},
    orderGoods: [],
    expressInfo: {},
    flag: false,

    handleOption: {},
    showType: 0 ,  //订单状态标识 0待确认 1待付款 2待发货 3已发货 4已收货
    files: [], //图片路径列表
    hasPicture: false,
    picUrls: [],
    progress:0,  //上传进度
    payRemarks:''
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    console.log("订单id："+options.id)
    console.log("编号：" + options.showType)
    this.setData({
      orderId: options.id,
      showType: options.showType
    });
    this.getOrderDetail();
  },
 onPullDownRefresh() {
  wx.showNavigationBarLoading() //在标题栏中显示加载
  this.getOrderDetail();
  wx.hideNavigationBarLoading() //完成停止加载
  wx.stopPullDownRefresh() //停止下拉刷新
 },
  getOrderExpress: function() {
    let that = this;
    util.request(api.ExpressQuery, {
      expCode: that.data.orderInfo.expCode,
      expNo: that.data.orderInfo.expNo
    }, 'POST').then(function(res) {
      if (res.errno === 0) {
        that.setData({
          expressInfo: res.data
        });

      }
    });
  },
  expandDetail: function() {
    let that = this;
    this.setData({
      flag: !that.data.flag
    })
  },
  getOrderDetail: function () {
    let that = this;
    util.request(api.OrderDetail, {
      orderId: that.data.orderId
    }).then(function (res) {
      if (res.errno === 0) {
        console.log(res.data);
        that.setData({
          orderInfo: res.data.orderInfo,
          orderGoods: res.data.orderGoods,
          // handleOption: res.data.orderInfo.handleOption
          endTime: new Date().getTime() + res.data.orderInfo.toMillis
        });
       
        util.timecutDown(that)
    // 请求物流信息,仅当订单状态为发货时才请求
    // if (res.data.orderInfo.handleOption.confirm) {
    //  that.getOrderExpress();
    // }
   }
  });
 },
 
 // “去付款”按钮点击效果
 payOrder: function(e) {
  let that = this;
   console.log('id:' + e.currentTarget.dataset.id)
  util.request(api.OrderPrepay, {
    orderId: e.currentTarget.dataset.id, payRemarks: that.data.payRemarks
  }, 'POST').then(function(res) {
   if (res.errno === 0) {
    const payParam = res.data;
    console.log("支付过程开始");
    wx.requestPayment({
     'timeStamp': payParam.timeStamp,
     'nonceStr': payParam.nonceStr,
     'package': payParam.packageValue,
     'signType': payParam.signType,
     'paySign': payParam.paySign,
     'success': function(res) {
      console.log("支付过程成功");
      util.redirect('/pages/ucenter/order/order');
     },
     'fail': function(res) {
      console.log("支付过程失败");
      util.showErrorToast('支付失败');
     },
     'complete': function(res) {
      console.log("支付过程结束")
     }
    });
   }
  });

  },
  // “取消订单”点击效果
  // cancelOrder: function () {
  //   let that = this;
  //   let orderInfo = that.data.orderInfo;

  //   wx.showModal({
  //     title: '',
  //     content: '确定要取消此订单？',
  //     success: function (res) {
  //       if (res.confirm) {
  //         util.request(api.OrderCancel, {
  //           orderId: orderInfo.id
  //         }, 'POST').then(function (res) {
  //           if (res.errno === 0) {
  //             wx.showToast({
  //               title: '取消订单成功'
  //             });
  //             util.redirect('/pages/ucenter/order/order');
  //           }
  //           else {
  //             util.showErrorToast(res.errmsg);
  //           }
  //         });
  //       }
  //     }
  //   });
  // },
  // // “取消订单并退款”点击效果
  // refundOrder: function () {
  //   let that = this;
  //   let orderInfo = that.data.orderInfo;

  //   wx.showModal({
  //     title: '',
  //     content: '确定要取消此订单？',
  //     success: function (res) {
  //       if (res.confirm) {
  //         util.request(api.OrderRefund, {
  //           orderId: orderInfo.id
  //         }, 'POST').then(function (res) {
  //           if (res.errno === 0) {
  //             wx.showToast({
  //               title: '取消订单成功'
  //             });
  //             util.redirect('/pages/ucenter/order/order');
  //           }
  //           else {
  //             util.showErrorToast(res.errmsg);
  //           }
  //         });
  //       }
  //     }
  //   });
  // },  
  // // “删除”点击效果
  // deleteOrder: function () {
  //   let that = this;
  //   let orderInfo = that.data.orderInfo;

  //   wx.showModal({
  //     title: '',
  //     content: '确定要删除此订单？',
  //     success: function (res) {
  //       if (res.confirm) {
  //         util.request(api.OrderDelete, {
  //           orderId: orderInfo.id
  //         }, 'POST').then(function (res) {
  //           if (res.errno === 0) {
  //             wx.showToast({
  //               title: '删除订单成功'
  //             });
  //             util.redirect('/pages/ucenter/order/order');
  //           }
  //           else {
  //             util.showErrorToast(res.errmsg);
  //           }
  //         });
  //       }
  //     }
  //   });
  // },  
  // // “确认收货”点击效果
  // confirmOrder: function () {
  //   let that = this;
  //   let orderInfo = that.data.orderInfo;

  //   wx.showModal({
  //     title: '',
  //     content: '确认收货？',
  //     success: function (res) {
  //       if (res.confirm) {
  //         util.request(api.OrderConfirm, {
  //           orderId: orderInfo.id
  //         }, 'POST').then(function (res) {
  //           if (res.errno === 0) {
  //             wx.showToast({
  //               title: '确认收货成功！'
  //             });
  //             util.redirect('/pages/ucenter/order/order');
  //           }
  //           else {
  //             util.showErrorToast(res.errmsg);
  //           }
  //         });
  //       }
  //     }
  //   });
  // },
  payRemarks:function(e){
    console.log(e.detail.value)
    this.setData({
      payRemarks: e.detail.value
    })
  },
  //图片上传==============
  //取消订单
  calOrder: function (e) {
    let id = e.currentTarget.dataset.id;
    let t = this;
    util.request(api.OrderCancel, {
      orderId: id
    }, "POST").then(function (res) {
      if (res.errno == 0) {
        t.onPullDownRefresh()
        wx.navigateTo({
          url: '/pages/ucenter/order/order',
        })
        wx.showToast({
          icon: 'success',
          title: '取消成功',
        })
      }
    });
  },
  //图片预览
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  }, 
  //选择图片
  chooseImage: function (e) {
    if (this.data.files.length >= 5) {
      util.showErrorToast('只能上传五张图片')
      return false;
    }
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
        that.upload(res);
      }
    })
  },
  //提交图片
  upload: function (res) {
    var that = this;
    const uploadTask = wx.uploadFile({
      url: api.StorageUpload,
      filePath: res.tempFilePaths[0],
      name: 'file',
      success: function (res) {
        var _res = JSON.parse(res.data);
        if (_res.errno === 0) {
          var url = _res.data.url
          that.data.picUrls.push(url)
          that.setData({
            hasPicture: true,
            picUrls: that.data.picUrls
          })
        }
      },
      fail: function (e) {
        wx.showModal({
          title: '错误',
          content: '上传失败',
          showCancel: false
        })
      },
    })

    uploadTask.onProgressUpdate((res) => {
      this.setData({
        progress: res.progress
      })
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })

  },
  //删除图片
  delImg:function(e){
    console.log("开始删除图片");
    console.log("图片id："+e.currentTarget.id);
    //splice（index，count，obj） 返回被删除的元素 
    console.log(this.data.files)
     this.data.files.splice(e.currentTarget.id,1);
   this.setData({
     files: this.data.files
   })
    console.log(this.data.files)
  },
  //提交付款凭证
  submitOrder:function(e){
    console.log(e)
    console.log("id:" + e.currentTarget.dataset.id)
    let that =this;
    if (that.data.picUrls.length <= 0){
      util.showErrorToast('请上传凭证！')
      return
    }
    util.request(api.OrderConfirm, { id: e.currentTarget.dataset.id, payRemarks: that.data.payRemarks, picUrls: that.data.picUrls,orderStatus: 1011 }, "POST").then(function (res) {
      if (res.errno === 0) {
        wx.showToast({
          success: 'success',
          title: '已成功确认',
        })
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          })
        }, 2000)
      }
    });
  },
  //确认收货
  confirmReceiveGoods:function(e){
    let that = this;
    if ('nopur'==this.data.orderInfo.payId){
      wx.setStorageSync('orderGoods', this.data.orderGoods);
      wx.navigateTo({
        url: '/pages/sale/sendGoods/sendGoods?nopur=' + this.data.orderInfo.payId,
      })
      console.log('未转采购')
      return
    }
    console.log('已转采购')
    console.log("id:" + e.currentTarget.dataset.id)
    util.request(api.OrderConfirm, { id: e.currentTarget.dataset.id, orderStatus: 104 }, "POST").then(function (res) {
      if (res.errno === 0) {
        wx.showToast({
          success: 'success',
          title: '已成功确认',
        })
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          })
        }, 2000)
      }
    });
  },
   //图片上传==============
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  }
})